package com.egg.gateway.filter;

import com.egg.common.util.PathMatchUtil;
import com.egg.gateway.config.WhiteConfig;
import com.egg.gateway.constant.FilterOrderConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * auth拦截
 *
 * @author east
 */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {


    @Autowired
    private WhiteConfig whiteConfig;


    @Override
    public int getOrder() {
        return FilterOrderConstant.AUTH_FILTER_ORDER;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (whiteConfig.excludeAuth(request.getURI().getPath())) {
            // 白名单接口, 直接放行
            return chain.filter(exchange);
        }
        // 获取请求上下文
        ContextFilter.GatewayContext gatewayContext = exchange.getAttribute(ContextFilter.GatewayContext.CACHE_GATEWAY_CONTEXT);
        if (null == gatewayContext) {
            // 如果没有上下文, 返回认证失败.
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        String method = request.getMethodValue();
        String path = request.getURI().getPath();
        String methodPath = (method + path).toLowerCase();
        if (gatewayContext.getFuncPerms().stream().anyMatch(o -> PathMatchUtil.isMatch(o, methodPath))) {
            return chain.filter(exchange);
        }
        // 没有获得权限, 返回授权失败
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }


}